package xjtu.se.articlecommunity.buser.login;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import xjtu.se.articlecommunity.buser.login.dto.BCodeLoginDto;
import xjtu.se.articlecommunity.buser.login.dto.BLoginDto;
import xjtu.se.articlecommunity.buser.login.impl.BLoginService;
import xjtu.se.articlecommunity.common.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/buser/login")
public class BLoginAPI {
    @Resource
    BLoginService service;

    @Resource
    private MailService mailService;

    @Resource
    private SMSService smsService;

    @Resource
    private CacheService cacheService;

    @RequestMapping("/passwordLogin")
    public Result login(@RequestBody BLoginDto dto){

        boolean confirm = service.checkLogin(dto);

        if(confirm){
            String token = TokenUtils.loginSign(dto.getU_key(),dto.getPassword(),1);
            return Result.success((Object)token);
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"id/邮箱/手机号或密码错误！");
    }


    @GetMapping("/mailcode")
    public Result mailcode(@RequestParam("mail") String mail) {
        if (service.checkMail(mail)) {
            log.info(mail);
            String mailcode = mailService.sendCode(mail);
            log.info(mailcode);
            cacheService.saveVerificationCode(mail, mailcode);
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"该邮箱未绑定管理员账号！");
    }

    @GetMapping("/telcode")
    public Result telcode(@RequestParam("tel") String tel) {
        if (service.checkTel(tel)) {
            log.info(tel);
            String telcode = smsService.sendVerificationCode(tel);
            log.info(telcode);
            cacheService.saveVerificationCode(tel, telcode);
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"该手机号未绑定管理员账号！");
    }

    @PostMapping("/mailcodeLogin")
    public Result Mlogin(@RequestBody BCodeLoginDto dto){
        if (cacheService.findVerificationCode(dto.getU_key()).equals(dto.getU_key())){
            String pwd = service.getPwd("u_mail",dto.getU_key());
            String token = TokenUtils.loginSign(dto.getU_key(), pwd,1);
            return Result.success((Object)token);
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"验证码错误！");
    }

    @PostMapping("/telcodeLogin")
    public Result Tlogin(@RequestBody BCodeLoginDto dto){
        if (cacheService.findVerificationCode(dto.getU_key()).equals(dto.getU_key())){
            String pwd = service.getPwd("u_tel",dto.getU_key());
            String token = TokenUtils.loginSign(dto.getU_key(), pwd,1);
            return Result.success((Object)token);
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"验证码错误！");
    }

    @PostMapping("/apply")
    public Result Apply(@RequestBody BLoginDto dto) {
        service.ApplyFor(dto);
        return Result.success();
    }
}
